package ch.unifr.diva.multimodals.spherex;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Vibrator;

public class MultimodalDialog {
	
	//Vibration settings
	public static final long VIBRATE_SHORT=100;
	public static final long VIBRATE_LONG=800;
	public static final long[]VIBRATE_PATTERN_SHORT={0,VIBRATE_SHORT,VIBRATE_SHORT,VIBRATE_SHORT,VIBRATE_SHORT,VIBRATE_SHORT};
	
	//Defining the sound identifiers
	public static int SOUND_POSITIVE;
	public static int SOUND_NEGATIVE1;
	public static int SOUND_NEGATIVE2;
	
	//Two approaches are possible: either using media player; otherwise use audio manager
private static boolean USE_MEDIA_PLAYER=false;
	
	
	private Vibrator vibrator;
	private SoundPool sounds=null;
	private AudioManager audioManager;
	private Context context;
	
	/**
	 * Auxiliary class to give feedback
	 * @param context The context in which feedbacks must be given
	 */
public MultimodalDialog(Context context){
	this.context=context;
	if(!USE_MEDIA_PLAYER){sounds=new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
	loadSounds();}
	audioManager = (AudioManager)context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
this.vibrator=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
}

/**
 * Method called to actually give feedback
 * @param positiveAnswer Whether or not the answer is positive or not
 * @param playSound Whether or not a sound should be replayed
 */
	public void confirm(boolean positiveAnswer, boolean playSound) {
		float streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		streamVolume = streamVolume / audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); //Divided to get a value [0.0;1.0]
		if(positiveAnswer){
			//Show that action was successful
			vibrator.vibrate(VIBRATE_PATTERN_SHORT,-1);
			if(playSound){
				if(USE_MEDIA_PLAYER)
				MediaPlayer.create(context, R.raw.positive).start();
				else
				    sounds.play(SOUND_POSITIVE, streamVolume, streamVolume, 1, 0, 1f);
			}
		}
		else{
			//Show that action was not successful
			vibrator.vibrate(VIBRATE_LONG);
			if(playSound){
				if(USE_MEDIA_PLAYER)
					MediaPlayer.create(context, R.raw.negative1).start();
				
					else
				sounds.play(SOUND_NEGATIVE1, streamVolume, streamVolume, 1, 0, 1f);
			}
		}
	}
	
	/**
	 * Provide very short, vibration only feedback
	 */
	public void shortConfirm(){
		vibrator.vibrate(VIBRATE_SHORT);
	}

	/**
	 * Initialization method
	 */
    private void loadSounds() {
		SOUND_POSITIVE=sounds.load(context, R.raw.positive, 1);
		SOUND_NEGATIVE1=sounds.load(context, R.raw.negative1, 1);
	}
}
